/**
 * 
 */
package team.helpmephone.app.main;

import java.util.Map;

import team.helpmephone.app.R;
import team.helpmephone.app.common.ConstantHelpMePhone;
import team.helpmephone.app.common.DaoHelpMePhone;
import team.helpmephone.app.common.HelpMePhoneAction;
import team.helpmephone.app.common.Utils;
import team.helpmephone.app.receiverUser.ActivityReceiverSetting;
import team.helpmephone.app.set.execute.ActivitySetExecute;
import team.helpmephone.app.set.message.ActivitySetMessage;
import team.helpmephone.app.set.pw.ActivitySetPw;
import team.helpmephone.app.set.record.ActivitySetRecordTime;
import team.helpmephone.app.set.sound.ActivitySetSound;
import team.helpmephone.app.set.time.ActivitySetTime;
import team.helpmephone.app.setLocation.ActivityLocationSetting;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

/**
 * Class : ActivityHelpMePhone.java<br>
 * Description: Help Me, Phone Main View.<br>
 * Copyright: Team HelpMe, Phone<br>
 * 
 * @author Jonghwa, Lee
 * @milestone 0.1
 * @created 2010. 2. 22.
 * @modified .
 * @sw_block Main View
 */
public class ActivityHelpMePhone extends Activity {

	public static final String TAG = "Help me, Phone Activity";
	private Resources resources;
	private AlertDialog.Builder builder;

	public static int CURRENT_STATE_STRING_RESOURCE_ID = R.string.standby;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.v(TAG, "onCreate()");
		Intent intent = getIntent();
		if (HelpMePhoneAction.ACTION_ACTIVE_CURRENT_STATE.equals(intent.getAction())) {
			
		} else {
			setContentView(R.layout.main);
			initialize();

			builder = new AlertDialog.Builder(this);			
		}
	}

	private void initialize() {
		Log.i(TAG, "Initailize DB");
		resources = getResources();

		Log.v(TAG, "Initailize Activity");
		TableLayout layout = (TableLayout) findViewById(R.id.MainLayout);
		for (int i = 0, max = layout.getChildCount(); i < max; i++) {
			View child = layout.getChildAt(i);
			child.setOnClickListener(eventHandle);
		}

		refresh();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		Log.i(TAG, "onActivityResult(), resultCode = " + resultCode);
		refresh();
	}

	
	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		finish();
	}

	private void refresh() {
		Log.i(TAG, "refresh()");

		inspectCurrentState();
		int currentStateStyleId = R.style.STANDBY_STATE;
		int currentStateDrawableId = R.drawable.standby_state;
		switch (CURRENT_STATE_STRING_RESOURCE_ID) {
		case R.string.test:
		case R.string.active:
			currentStateDrawableId = R.drawable.active_state;
			currentStateStyleId = R.style.ACTIVIE_STATE;
			break;
		case R.string.perceive:
			currentStateDrawableId = R.drawable.perceive_state;
			currentStateStyleId = R.style.PERCEIVE_STATE;
			break;
		}

		Map<String, String> data = DaoHelpMePhone.getInstance().getAll(this);
		TableLayout layout = (TableLayout) findViewById(R.id.MainLayout);
		for (int i = 0, max = layout.getChildCount(); i < max; i++) {
			TableRow row = (TableRow) layout.getChildAt(i);
			for (int j = 0, children = row.getChildCount(); j < children; j++) {
				View view = row.getChildAt(j);

				TextView textView = (TextView) view;
				textView.setBackgroundResource(currentStateDrawableId);
				textView.setTextAppearance(getApplicationContext(), currentStateStyleId);
				if (view.getId() == View.NO_ID) {
					continue;
				}

				String value = data.get(resources.getResourceEntryName(view.getId()));
				if (view.getId() == R.id.RECEIVER_TEXT) {
					if (value.indexOf("/") == ConstantHelpMePhone.DONT_CARE) {
						String[] temp = value.split(",");
						value = temp[0];
					} else {
						String[] temps = value.split("/");
						StringBuilder builder = new StringBuilder();
						for(String temp : temps) {
							String[] name = temp.split(",");
							builder.append(name[0]).append("\n");
						}
						value = builder.substring(0, builder.length() - 1);
					}
				}
				textView.setText(Utils.isExistingField(value) ? value : resources.getString(R.string.unset));
				textView.setGravity(view.getId() == R.id.SEND_MESSAGE_TEXT ? Gravity.NO_GRAVITY : Gravity.CENTER_HORIZONTAL);
			}
		}
	}

	private int inspectCurrentState() {
		Log.v(TAG, "inspectCurrentState()");
		String currentState = DaoHelpMePhone.getInstance().get(this, resources.getResourceEntryName(R.id.CURRENT_STATE_TEXT));
		if (!Utils.isExistingField(currentState)) {
			CURRENT_STATE_STRING_RESOURCE_ID = R.string.standby;
		}

		if (currentState.equals(resources.getString(R.string.test))) {
			CURRENT_STATE_STRING_RESOURCE_ID = R.string.test;
		} else if (currentState.equals(resources.getString(R.string.active))) {
			CURRENT_STATE_STRING_RESOURCE_ID = R.string.active;
		} else if (currentState.equals(resources.getString(R.string.perceive))) {
			CURRENT_STATE_STRING_RESOURCE_ID = R.string.perceive;
		} else if (currentState.equals(resources.getString(R.string.standby))) {
			CURRENT_STATE_STRING_RESOURCE_ID = R.string.standby;
		} else {
			CURRENT_STATE_STRING_RESOURCE_ID = R.string.all_clear;
		}

		return CURRENT_STATE_STRING_RESOURCE_ID;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		Log.v(TAG, "onCreateDialog(), id = " + id);
		builder.setTitle(R.string.current_state);
		switch (id) {
		case R.string.test:
		case R.string.active:
			builder.setSingleChoiceItems(resources.getTextArray(R.array.ACTIVE_STATE_ITEMS), 1, dialogHandler);
			break;
		default:
			int selectedId = 0;
			if (id == R.string.test) {
				selectedId = 0;
			} else if (id == R.string.perceive) {
				selectedId = 1;
			} else if (id == R.string.standby) {
				selectedId = 2;
			} else {
				selectedId = 3;
			}
			builder.setSingleChoiceItems(resources.getTextArray(R.array.NORMAL_STATE_ITEMS), selectedId, dialogHandler);
			break;
		}
		return builder.create();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
	 */
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		Log.v(TAG, "onPrepareDialog(), id = " + id);
		int selectedId = 0;
		switch (id) {
		case R.string.test:
		case R.string.active:
			selectedId = 1;
			break;
		default:
			if (id == R.string.test) {
				selectedId = 0;
			} else if (id == R.string.perceive) {
				selectedId = 1;
			} else if (id == R.string.standby) {
				selectedId = 2;
			} else {
				selectedId = 3;
			}
			break;
		}

		AlertDialog aDialog = (AlertDialog) dialog;
		ListView listView = aDialog.getListView();
		if (listView != null) {
			listView.setItemChecked(selectedId, true);
		}
	}

	private Activity getThis() {
		return this;
	}
	
	private DialogHandler dialogHandler = new DialogHandler();

	private class DialogHandler implements DialogInterface.OnClickListener {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
		 */
		public void onClick(DialogInterface dialog, int which) {
			Log.v(TAG, "DialogHandler onClick(), which = " + which);
			int dialogId = CURRENT_STATE_STRING_RESOURCE_ID;
			if (CURRENT_STATE_STRING_RESOURCE_ID == R.string.active || CURRENT_STATE_STRING_RESOURCE_ID == R.string.test) {
				switch (which) {
				case 0:
					CURRENT_STATE_STRING_RESOURCE_ID = R.string.active;
					break;
				default:
					CURRENT_STATE_STRING_RESOURCE_ID = R.string.all_clear;
					sendBroadcast(new Intent(HelpMePhoneAction.ACTION_CLEAR_CURRENT_STATE));
					break;
				}
			} else {
				switch (which) {
				case 0:
					CURRENT_STATE_STRING_RESOURCE_ID = R.string.test;
					sendBroadcast(new Intent(HelpMePhoneAction.ACTION_ACTIVE_CURRENT_STATE));
					break;
				case 1:
					CURRENT_STATE_STRING_RESOURCE_ID = R.string.perceive;
					sendBroadcast(new Intent(HelpMePhoneAction.ACTION_PERCEIVE_CURRENT_STATE));
					break;
				case 2:
					CURRENT_STATE_STRING_RESOURCE_ID = R.string.standby;
					sendBroadcast(new Intent(HelpMePhoneAction.ACTION_STANDBY_CURRENT_STATE));
					break;
				case 3:
				default:
					CURRENT_STATE_STRING_RESOURCE_ID = R.string.all_clear;
					sendBroadcast(new Intent(HelpMePhoneAction.ACTION_CLEAR_CURRENT_STATE));
					break;
				}
			}

			dismissDialog(dialogId);
			DaoHelpMePhone.getInstance().set(getThis(), resources.getResourceEntryName(R.id.CURRENT_STATE_TEXT), resources.getString(CURRENT_STATE_STRING_RESOURCE_ID));
			refresh();
		}
	}

	private TableEventListener eventHandle = new TableEventListener();

	private class TableEventListener implements OnClickListener {
		private void doAction(int id) {
			String activityName = resources.getResourceEntryName(id);
			Log.v(TAG, "TableEventListener, doAction(), id = " + id + ", activity name = " + activityName);
			Intent intent = null;
			switch (id) {
			case R.id.CURRENT_STATE_TEXT:
				showDialog(inspectCurrentState());
				return;
			case R.id.MOTION_CAPTURE_TEXT:
				intent = new Intent(getApplicationContext(), ActivitySetExecute.class);
				break;
			case R.id.CAPTURE_TIME_TEXT:
				intent = new Intent(getApplicationContext(), ActivitySetTime.class);
				break;
			case R.id.CAPTURE_LOCATION_TEXT:
				intent = new Intent(getApplicationContext(), ActivityLocationSetting.class);
				break;
			case R.id.WARNING_BELL_TEXT:
				intent = new Intent(getApplicationContext(), ActivitySetSound.class);
				break;
			case R.id.RECORD_TIME_TEXT:
				intent = new Intent(getApplicationContext(), ActivitySetRecordTime.class);
				break;
			case R.id.RECEIVER_TEXT:
				intent = new Intent(getApplicationContext(), ActivityReceiverSetting.class);
				break;
			case R.id.SEND_MESSAGE_TEXT:
				intent = new Intent(getApplicationContext(), ActivitySetMessage.class);
				break;
			case R.id.PW_TEXT:
				intent = new Intent(getApplicationContext(), ActivitySetPw.class);
				break;
			default:
				return;
			}

			if (intent == null) {
				return;
			}

			intent.putExtra(DaoHelpMePhone.COLUMN_ACTIVITY_NAME, activityName);
			startActivityForResult(intent, id);
		}

		public void onClick(View v) {
			if (!(v instanceof TableRow)) {
				return;
			}

			TableRow row = (TableRow) v;
			doAction(row.getChildAt(1).getId());
		}
	}
}
